package com.topnav.mc.listener;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.topnav.mc.admin.entity.Device;
import com.topnav.mc.admin.service.IDeviceService;
import com.topnav.mc.listener.bean.DeviceStatus;
import com.topnav.mc.uitls.DeviceOnlineUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.stereotype.Component;

/**
 * 接收设备心中通知
 * @Author: kenny
 * @Date: 2023/10/31 18:10
 */
@Component
@Slf4j
public class RedisDeviceKeepaliveListener implements MessageListener {
    @Autowired
    private DeviceOnlineUtils deviceOnlineUtils;
    @Autowired
    private IDeviceService deviceService;

    @Override
    public void onMessage(Message message, byte[] bytes) {
        log.info("******* 收到设备心跳通知 {}",message.toString());
        JSONObject jsonObject = JSON.parseObject(message.getBody(), JSONObject.class);
        Device device = deviceService.getFromCache(jsonObject.get("deviceId").toString());
        if (device != null){
            if (device.getOnline()){
                deviceOnlineUtils.setOnline(device.getCode());
            }else{
                deviceOnlineUtils.deviceStatusEvent(device,1, "设备主动");
            }
        }
    }
}
